<template>
    <div>
        <Window :show="windowConfig.show" :buttons="windowConfig.buttons" @close="closeWindow">
            <el-form :model="blogFormData" :rules="rules" ref="blogFormRef">
                <el-form-item props="title">
                    <div class="title-input">
                        <el-input placeholder="请输入博客标题" v-model="blogFormData.title"></el-input>
                    </div>
                </el-form-item>
                <el-form-item props="content">
                    <div :style="{ 'width': '100%' }">
                        <EditorMarkdown :height="editorHeight" v-model="blogFormData.markdownContent"
                                        @htmlContent="setHtmlContent"></EditorMarkdown>
                    </div>
                </el-form-item>
            </el-form>
            <!--  <EditorHtml :height="editorHtmlHeight"></EditorHtml> -->
            <el-dialog v-model="dialogVisible" title="编辑博客" width="30%" draggable>
                <!-- 第一个段落 - 下拉列表选择博客分类 -->
                <el-select v-model="selectedCategoryId" placeholder="请选择博客分类"
                           style="margin-bottom: 10px; height: 30px; font-size: 16px;">
                    <el-option v-for="category in categoryList" :label="category.categoryName"
                               :value="category.categoryId"
                               :key="category.id">
                    </el-option>
                </el-select>

                <!-- 第二个段落 - 封面-->
                <CoverUpload v-model="settingData.cover" @update:filename="onFilenameUpdate"></CoverUpload>

                <!-- 第三个段落 - 输入简介 -->
                <el-input v-model="settingData.categoryDesc" placeholder="简介" class="multiline-input" type="textarea"
                          :autosize="{ minRows: 4, maxRows: 4 }" :maxlength="300" style="margin-bottom: 1px;"/>
                <!-- 是否支持评论开关 -->
                <div style="display: flex; align-items: center;">
                    <p :style="{ 'font-size': '15px' }">是否支持评论：</p>
                    <el-radio-group v-model="settingData.allowComment">
                        <el-radio label="1">是</el-radio>
                        <el-radio label="0">否</el-radio>
                    </el-radio-group>
                </div>
                <div style="display: flex; align-items: center;">
                    <p :style="{ 'font-size': '15px' }">是否发布：</p>
                    <el-radio-group v-model="settingData.allowIssue">
                        <el-radio label="1">是</el-radio>
                        <el-radio label="0">否</el-radio>
                    </el-radio-group>
                </div>

                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="handleSave">确定</el-button>
                    </span>
                </template>
            </el-dialog>

        </Window>
    </div>
</template>

<script setup>
    import {reactive, onMounted, ref, nextTick} from 'vue';
    import axios from 'axios';

    const jwtToken = localStorage.getItem('jwtToken');

    const axiosInstance = axios.create({
        headers: {
            'Token': jwtToken // 将JWT令牌放入请求头的token字段
        }
    });
    const currentTime = new Date(); // 如果你使用原生的 Date 对象
    const editorHeight = window.innerHeight - 300;
    const editorHtmlHeight = window.innerHeight - 280;
    const dialogVisible = ref(false)
    const categoryList = ref([]);
    const selectedCategoryId = ref(null);
    const oldCategoryId = ref(null);
    const newCategoryId = ref(null);
    axiosInstance.get('http://localhost:8080/show')
        .then(response => {
            const responseData = response.data;
            if (Array.isArray(responseData.data) && responseData.data.length > 0) {
                // 使用 map 函数提取每行数据的 categoryName
                categoryList.value = responseData.data;
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
        });
    //markdown编辑器设置html内容
    const setHtmlContent = (htmlContent) => {
        blogFormData.markdownContent = htmlContent;
        blogData.content = blogFormData.markdownContent;// 更新你的数据
    }
    //新增博客的按键逻辑
    const init = (type, data) => {
        windowConfig.show = true;
        nextTick(() => {
            if (type === "add") {
                blogData = [];
            }
        })
    }

    //查询回调，编辑的按键逻辑
    const init2 = (blogId) => {
        windowConfig.show = true;
        axiosInstance.get(`http://localhost:8080/showdata/${blogId}`)
            .then(response => {
                const responseData = response.data;
                blogFormData.value.title = responseData.data.title;
                blogFormData.value.markdownContent = responseData.data.content;
                settingData.cover = responseData.data.cover;
                settingData.categoryDesc = responseData.data.description;
                settingData.allowComment = responseData.data.status;
                settingData.allowIssue = responseData.data.allowIssue
                settingData.statusName = responseData.data.statusName
                selectedCategoryId.value = responseData.data.categoryId;
                // 设置博客的唯一标识符，通常是博客的ID
                blogData.blogId = blogId;
                oldCategoryId.value = selectedCategoryId.value;
            })
            .catch(error => {
                console.error('请求失败:', error);
            });
    }
    defineExpose({init, init2});
    //博客设置
    const windowConfig = reactive({
        show: false,
        title: "标题",
        buttons: [{
            type: "success",
            text: "确定",
            click: (e) => {
                submitBlog();
            }
        }]
    })
    //展示弹窗
    const blogFormRef = ref(null);
    const blogFormData = ref({
        title: "",
        markdownContent: ""
    });
    const submitBlog = () => {
        dialogVisible.value = true;
        blogData.title = blogFormData.value.title;
    }
    const closeWindow = () => {
        windowConfig.show = false;

    }
    const formData = ref({});


    //博客正文
    const rules = {
        title: [{required: true, message: "请输入标题"}],
        content: [{required: true, message: "请输入正文"}],
        categoryName: [{required: true, message: "请输入博客分类"}],
        allowComment: [{required: true, message: "请输入是否允许评论"}],
    }
    const settingData = reactive({
        cover: "", // 使用空字符串初始化 cover 属性
        categoryName: "",
        categoryDesc: "",
        selectedId: "",// 设置默认值为空字符串
        allowIssue: ""
    });

    const blogData = ref({
        cover: "",
        categoryName: "",
        title: "",
        writer: "", // 确保writer的值被正确设置
        allowComment: "",
        status: "",
        content: "",
        description: "",
        categoryId: "",
        allowIssue: "",
        statusName: "",
        time: ""
    });
    onMounted(() => {
        // 获取令牌信息
        const jwtToken = localStorage.getItem('jwtToken');
        if (jwtToken) {
            // 解码JWT令牌（假设它是一个包含用户名的 JSON）
            const tokenData = JSON.parse(decodeURIComponent(escape(atob(jwtToken.split('.')[1]))));
            blogData.writer = tokenData.username;
        }
    });
    //获取到封面
    const onFilenameUpdate = (filename) => {
        // 在这里获取到新的 filename
        console.log('New filename:', filename);
        blogData.cover = filename;
        // 更新 form.cover 或执行其他操作
    }
    //弹窗确定
    const handleSave = () => {
        // 通过 .value 访问数组
        const selectedCategory = categoryList.value.find(category => category.categoryId === selectedCategoryId.value);
        blogData.cover = settingData.cover;
        blogData.allowComment = settingData.allowComment === '1' ? '允许' : '不允许';
        blogData.status = settingData.allowComment === '1' ? 1 : 0;
        blogData.statusName = settingData.allowIssue === '1' ? '已发布' : '未发布';
        blogData.allowIssue = settingData.allowIssue === '1' ? 1 : 0;
        blogData.categoryName = selectedCategory.categoryName;
        blogData.categoryId = selectedCategoryId.value;
        blogData.description = settingData.categoryDesc;
        const options = {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        };

        const formattedTime = currentTime.toLocaleString(undefined, options);
        blogData.time = formattedTime;
        console.log(blogData.time, 66666666)
        newCategoryId.value = blogData.categoryId
        if (blogData.blogId) {
            // 这里执行更新操作
            updateCategory();
            updateCategory2();
            updateBlog();
        } else {
            // 这里执行创建操作
            createBlog();
        }
    };
    // 创建博客
    const createBlog = () => {
        // 做创建操作的逻辑，向后端发送创建请求
        axiosInstance.post('http://localhost:8080/insert', blogData)
            .then(response => {
                console.log('创建成功', response);
                alert("创建成功");
                location.reload();
            })
            .catch(error => {
                console.error('创建失败', error);
                // 在这里可以根据需要处理错误
            });
        axiosInstance.post('http://localhost:8080/es/addBlog', blogData)
            .then(response => {
                console.log('插入es成功', response);
            })
            .catch(error => {
                console.error('创建失败', error);
                // 在这里可以根据需要处理错误
            });

    };
    // 更新博客内容
    const updateBlog = () => {
        // 做更新操作的逻辑，向后端发送更新请求
        // 使用 blogData.blogId 发送请求到对应的博客 ID
        axiosInstance.put(`http://localhost:8080/updateblog/${blogData.blogId}`, blogData)
            .then(response => {
                console.log('更新成功', response);
                alert("更新成功");
                location.reload();
            })
            .catch(error => {
                console.error('更新失败', error);
                // 在这里可以根据需要处理错误
            });
        console.log(blogData);
    };
    //更新分类
    const updateCategory = () => {
        // 做更新操作的逻辑，向后端发送更新请求
        // 使用 blogData.blogId 发送请求到对应的博客 ID
        axiosInstance.put(`http://localhost:8080/updateCategory/${oldCategoryId.value}`)
            .then(response => {
                console.log('更新成功', response);
                console.log(oldCategoryId, newCategoryId, 6666666666666666666666666)
            })
            .catch(error => {
                console.error('更新失败', error);
                // 在这里可以根据需要处理错误
            });
    };
    const updateCategory2 = () => {
        // 做更新操作的逻辑，向后端发送更新请求
        // 使用 blogData.blogId 发送请求到对应的博客 ID
        axiosInstance.put(`http://localhost:8080/updateCategory2/${newCategoryId.value}`)
            .then(response => {
                console.log('更新成功', response);
            })
            .catch(error => {
                console.error('更新失败', error);
                // 在这里可以根据需要处理错误
            });
    };
    // 删除按钮点击时执行的逻辑
    const handleDelete = (row) => {
    };
</script>

<style lang="scss">
    .title-input {
        width: 100%;
        border-bottom: 1px solid #ddd;

        .el-input__wrapper {
            box-shadow: none;
        }

        input {
            font-size: 20px;
        }
    }
</style>